/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ke.me.muhia.spring.masomo.provisioning.xmlrpc;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcStreamTransport;
import org.apache.xmlrpc.client.XmlRpcSunHttpTransport;
import org.apache.xmlrpc.common.XmlRpcStreamRequestConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

/**
 *
 * @author Kenneth
 */
public class MessageLoggingTransport extends XmlRpcSunHttpTransport{
    
    private static final Logger logger = LoggerFactory.getLogger(MessageLoggingTransport.class);

    public MessageLoggingTransport(XmlRpcClient pClient) {
        super(pClient);
    }
    
    /**
     * 
     * @param pWriter
     * @throws IOException
     * @throws XmlRpcException
     * @throws SAXException 
     */
    
    @Override
    protected void writeRequest(XmlRpcStreamTransport.ReqWriter pWriter) throws IOException, XmlRpcException, SAXException
    {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        pWriter.write(baos);
        logger.debug(baos.toString());
        super.writeRequest(pWriter);
    }
    
    /**
     * 
     * @param pConfig
     * @param pStream
     * @return
     * @throws XmlRpcException 
     */
    @Override
    protected Object readResponse(XmlRpcStreamRequestConfig pConfig, InputStream pStream) throws XmlRpcException
    {
        final StringBuffer sb = new StringBuffer();

        try
        {
            final BufferedReader reader = new BufferedReader(new InputStreamReader(pStream));
            String line = reader.readLine();
            while(line != null)
            {
                sb.append(line);
                line = reader.readLine();
            }
        }
        catch(final IOException e)
        {
            logger.error(e.getMessage(), e);
        }

        logger.debug(sb.toString());

        final ByteArrayInputStream bais = new ByteArrayInputStream(sb.toString().getBytes());
        return super.readResponse(pConfig, bais);
    }


    
    
    
}
